package com.xgame.server.dbtool;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xgame.server.db.mapper.AccountMapper;
import com.xgame.server.db.mapper.AccountbindMapper;
import com.xgame.server.db.mapper.UserMapper;
import com.xgame.server.db.model.Account;
import com.xgame.server.db.model.Accountbind;
import com.xgame.server.db.model.User;
import com.xgame.server.netty.proto.Game;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

@Component
public class AccountCsTool {

    @Resource
    private UserMapper userMapper;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private AccountbindMapper accountbindMapper;

    //插入用户数据
    public Integer insertUser(String account, String pwd, String identify) {
        User user = new User();
        user.setAccount(account);
        user.setPwd(pwd);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setRegisterTime(df.format(System.currentTimeMillis()));

        Accountbind bind = new Accountbind();
        bind.setIdentify(identify);
        bind.setAccount(account);

        accountbindMapper.insert(bind);
        return userMapper.insert(user);
    }

    //插入玩家数据
    public Integer insertAccount(Game.AccountDataCS data) throws Exception {
        //1.更新用户表
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", data.getAccount());

        User user = new User();
        user.setPlayerId(data.getPlayerID());
        user.setLastUpTime(df.format(System.currentTimeMillis()));
        user.setGame(data.getPlatform());
        userMapper.update(user, userWrapper);

        //2.向表中添加数据
        Account account = new Account();
        account.setAccount(data.getAccount());
        account.setPlayerId(data.getPlayerID());
        account.setIdentify(data.getIdentify());
        account.setRoleName(data.getRoleName());
        account.setLevel(data.getLevel());
        account.setExp(new Long(data.getExp()));
        account.setCoin(data.getCoin());
        account.setDiamond(data.getDiamond());
        account.setTotalRecharge(data.getTotalRecharge());
        account.setValidDiamond(data.getValidDiamond());
        account.setLimit(data.getLimit());
        account.setCard1(data.getCard1());
        account.setCard2(data.getCard2());
        account.setCard3(data.getCard3());

        return accountMapper.insert(account);
    }

    //检查是否有重复的identify，唯一标识
    public boolean checkIdentify(String identify) throws Exception {

        if ("" == identify) {
            return false;
        }
        EntityWrapper<Accountbind> userWrapper = new EntityWrapper<>();
        userWrapper.eq("identify", identify);

        List<Accountbind> users = accountbindMapper.selectList(userWrapper);

        return users.size() > 0;
    }

    //检查玩家上次备份的时间，如果不超过3分钟
    public boolean checkValidDate(Game.AccountDataCS data) throws Exception {
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", data.getAccount());

        List<User> users = userMapper.selectList(userWrapper);
        if (users.size() != 1) {
            return false;
        } else {

            String toDate = sf2.format(System.currentTimeMillis());

            Long from = sf1.parse(users.get(0).getLastUpTime()).getTime();
            Long to = sf2.parse(toDate).getTime();
            Long seconds = (to - from) / (1000);

            return seconds > 600;
        }
    }

    //更新玩家数据，用在上传存档的时候
    public void updateAccount(Game.AccountDataCS data) throws Exception {
        //1.更新用户表
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", data.getAccount());

        List<User> users = userMapper.selectList(userWrapper);
        User user = null;

        if (users.size() > 0) {
            user = users.get(0);
        } else {
            user = new User();
        }

        user.setLastUpTime(df.format(System.currentTimeMillis()));

        userMapper.update(user, userWrapper);

        //2.向表中添加数据
        EntityWrapper<Account> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("account", data.getAccount());

        Account account = new Account();
        account.setPlayerId(data.getPlayerID());
        account.setRoleName(data.getRoleName());
        account.setLevel(data.getLevel());
        account.setExp(new Long(data.getExp()));
        account.setCoin(data.getCoin());
        account.setDiamond(data.getDiamond());
        account.setIdentify(data.getIdentify());
        account.setTotalRecharge(data.getTotalRecharge());
        account.setValidDiamond(data.getValidDiamond());
        account.setLimit(data.getLimit());
        account.setCard1(data.getCard1());
        account.setCard2(data.getCard2());
        account.setCard3(data.getCard3());

        accountMapper.update(account, entityWrapper);
    }

    //原理：在玩家备份游戏的时候，如果进行备份的游戏账号无游戏数据，或者之前账号等级为15~20级，
    // 且账号创建时间距离当前备份时间超过了一个月，并且账号的等级超过了35级，就禁止备份
    public int checkHasValidAccount(Game.AccountDataCS data) throws Exception {

        //1.获取User信息
        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", data.getAccount());

        List<User> users = userMapper.selectList(userWrapper);
        User user = null;

        if (users.size() > 0) {
            user = users.get(0);
        }

        //2.获取Account信息
        EntityWrapper<Account> accountWrapper = new EntityWrapper<>();
        accountWrapper.eq("account", data.getAccount());

        List<Account> accounts = accountMapper.selectList(accountWrapper);
        Account account = null;

        if (accounts.size() > 0) {
            account = accounts.get(0);
        }


        if(data.getBackupflag()== 0)
        {
            //加入验证唯一设备，采取和上一次备份的设备号对比，如果设备号不一样
            if (account != null && !account.getIdentify().equals(data.getIdentify()))
            {
                return 3;
            }
        }

        //3.判定是否超过30天没有
        if (!checkRegisDays(data.getAccount(), 28)) {
            //没有超过28天,就要看第一次备份时候是否一下备份的大数据
            if (user != null && user.getPlayerId() == null || user.getLastUpTime() == null || user.getPlayerId().isEmpty() || user.getLastUpTime().isEmpty()) {
                //如果备份过数据，再判断玩家的等级区间，防止那种玩家玩到15级进行备份的
                if (data.getLevel() > 70) {
                    return 4;
                } else {
                    return 0;
                }
            } else {
                return 0;
            }
        } else {
            //超过了28天，检查是否有备份过数据
            if (user != null && user.getPlayerId() != null && user.getLastUpTime() != null && !user.getPlayerId().isEmpty() && !user.getLastUpTime().isEmpty()) {
                //如果备份过数据，再判断玩家的等级区间，防止那种玩家玩到15级进行备份的
                if (account != null && account.getLevel() > 17) {
                    return 0;
                } else {
                    if (data.getLevel() < 34) {
                        return 0;
                    }
                    return 4;
                }
            } else {
                //超过28天，低于32级的可以备份
                if (data.getLevel() < 33) {
                    return 0;
                }
                return 4;
            }
        }

        /*
        EntityWrapper<Account> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", account);

        List<Account> accounts = accountMapper.selectList(userWrapper);

        boolean ok = true;

        for (int i = 0; i < accounts.size(); i++) {
            String temp = accounts.get(i).getPlayerId();
            if (!temp.equals(playerId)) {
                ok = false;
                break;
            }
        }

        return ok;
         */
    }

    //根据账号密码查询用户
    public Integer selectUserByAccountSize(String account, String pwd) throws Exception {
        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", account);
        userWrapper.eq("pwd", pwd);

        return userMapper.selectList(userWrapper).size();
    }

    //根据账号查询用户
    public Integer selectUserByAccountSize(String account) throws Exception {
        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", account);

        return userMapper.selectMaps(userWrapper).size();
    }

    //获取用户数据
    public List<Account> selectAccountByAccount(String account) throws Exception {
        EntityWrapper<Account> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", account);

        return accountMapper.selectList(userWrapper);
    }

    //获取玩家已经下载的次数
    public Integer getOptionCount(String account) throws Exception {
        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", account);
        List<User> ddb = userMapper.selectList(userWrapper);

        Integer result = 0;

        if (ddb.size() != 0) {
            result = ddb.get(0).getMonthOptionCount();
        }

        return result;
    }

    //检查同一个id的有几个
    public boolean checkValidAccount(String account) throws Exception {
        List<Account> data = selectAccountByAccount(account);
        if (data.size() == 0) {
            throw new Exception();
        }

        Account act = data.get(0);

        EntityWrapper<Account> userWrapper = new EntityWrapper<>();
        userWrapper.eq("player_id", act.getPlayerId());

        List<Account> players = accountMapper.selectList(userWrapper);

        if (players.size() > 1) {
            return false;
        }

        return true;
    }

    //获取玩家账号注册的间隔的天数
    public boolean checkRegisDays(String account, int day) throws Exception {
        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", account);

        List<User> users = userMapper.selectList(userWrapper);

        SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (users.size() != 1) {
            return false;
        } else {

            String toDate = sf2.format(System.currentTimeMillis());

            Long from = sf1.parse(users.get(0).getRegisterTime()).getTime();
            Long to = sf2.parse(toDate).getTime();
            Long days = (to - from) / (1000 * 3600 * 24);

            return days > day;
        }


    }

    //玩家下载次数以及更新时间进行更新
    public void updateOptionCount(String account) throws Exception {
        Integer count = getOptionCount(account);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        EntityWrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("account", account);

        List<User> users = userMapper.selectList(userWrapper);
        User user = null;

        if (users.size() > 0) {
            user = users.get(0);
        } else {
            user = new User();
        }

        user.setLastDownTime(df.format(System.currentTimeMillis()));
        user.setMonthOptionCount(count + 1);

        userMapper.update(user, userWrapper);
    }

}
